const mysql = require('mysql2/promise');
const jwt = require('jsonwebtoken');
const { secret } = require('../config/jwt');

async function testBookshelf() {
  console.log('🔍 开始测试书架功能...\n');

  // 创建数据库连接
  const connection = await mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'uni_library'
  });

  try {
    // 1. 检查用户
    const [users] = await connection.execute('SELECT id, username FROM users LIMIT 1');
    if (users.length === 0) {
      console.log('❌ 没有用户，请先创建用户');
      return;
    }
    const user = users[0];
    console.log(`✅ 找到用户: ${user.username} (ID: ${user.id})`);

    // 2. 检查图书
    const [books] = await connection.execute('SELECT id, name FROM books WHERE id IN (20, 21, 22, 23, 24, 25, 26) LIMIT 7');
    console.log(`✅ 找到 ${books.length} 本测试图书:`);
    books.forEach(book => console.log(`  - ID: ${book.id}, 名称: ${book.name}`));

    // 3. 测试直接数据库操作
    console.log('\n📖 测试直接数据库操作...');
    for (const book of books.slice(0, 3)) {  // 只测试前3本
      try {
        // 检查是否已在书架中
        const [existing] = await connection.execute(
          'SELECT id FROM bookshelf WHERE user_id = ? AND book_id = ?',
          [user.id, book.id]
        );

        if (existing.length > 0) {
          console.log(`ℹ️  图书 ${book.name} (ID: ${book.id}) 已在书架中`);
        } else {
          // 添加到书架
          await connection.execute(
            'INSERT INTO bookshelf (user_id, book_id) VALUES (?, ?)',
            [user.id, book.id]
          );
          console.log(`✅ 图书 ${book.name} (ID: ${book.id}) 添加到书架成功`);
        }
      } catch (error) {
        console.log(`❌ 图书 ${book.name} (ID: ${book.id}) 添加失败:`, error.message);
      }
    }

    console.log('\n🎉 数据库测试完成！');

  } catch (error) {
    console.error('❌ 测试失败:', error);
  } finally {
    await connection.end();
  }
}

// 运行测试
testBookshelf().catch(console.error);
